package com.coocaa.x.provider.xprovider;

import android.content.ContentResolver;
import android.content.Context;
import android.database.Cursor;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.coocaa.x.framework.utils.Android;
import com.coocaa.x.framework.utils.LiteURI;
import com.coocaa.x.framework.utils.LogUtils;
import com.coocaa.x.provider.ProviderData;

import java.util.List;

/**
 * Created by lu on 15-12-22.
 */
public class XProviderManager {
    public static String URI_AUTHORITY = null;

    public static synchronized void init(Context c) {
        if (URI_AUTHORITY == null) {
            URI_AUTHORITY = (String) Android.getMetaData(c, c.getPackageName(), "PROVIDER_AUTH");
            LogUtils.d("XProviderManager", "URI_AUTHORITY:" + URI_AUTHORITY);
        }
        if (cr == null)
            cr = c.getContentResolver();
    }


    public enum PROVIDER_PATH {
        BLACKLIST("blacklist");

        public String path;

        PROVIDER_PATH(String path) {
            this.path = path;
        }
    }


    private static final String URI_FORMAT = "content://%s/%s";
    private static ContentResolver cr = null;

    private static LiteURI createUri(String auth, String path) {
        LiteURI uri = LiteURI.create(String.format(URI_FORMAT, auth, path));
        return uri;
    }

    public static List<Object> getBlackList() {
        Cursor c = cr.query(createUri(URI_AUTHORITY, PROVIDER_PATH.BLACKLIST.path).toUri(), null, null, null, null);
        String value = ProviderData.getValueCursorValue(c);
        try {
            LogUtils.d("lam", "getBlackList  value:" + value);
            JSONArray array = JSONObject.parseArray(value);
            return array.subList(0, array.size());
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }

    public static void updateBlackList() {
        cr.update(createUri(URI_AUTHORITY, PROVIDER_PATH.BLACKLIST.path).toUri(), null, null, null);
    }
}
